package top.korori.uitls;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.korori.common.utils.JwtUtils;
import top.korori.constant.AuthConstant;

import javax.servlet.http.HttpServletRequest;

/**
 * 前台用户工具类
 */
public class SvSecurityUtil {


    /**
     * 获取前台用户id
     * @return 前台用户id
     */
    public static Long getUserId(){

        ServletRequestAttributes servletRequestAttributes =  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert servletRequestAttributes != null;
        HttpServletRequest request = servletRequestAttributes.getRequest();

        String secret = SpringUtil.getProperty("sv.token.secret");

        String token = request.getHeader(AuthConstant.HEADER);
        String jwtToken = StrUtil.replace(token, AuthConstant.TOKEN_PREFIX, "");
        DecodedJWT decodedJWT = JwtUtils.verify(jwtToken, secret);
        if (ObjUtil.isNull(decodedJWT)) return null;
        return decodedJWT.getClaim(AuthConstant.JWT_UID).asLong();

    }

}
